import themeChangeBehavior from 'tdesign-miniprogram/mixins/theme-change';
const pagePermissionMixin = require('../../utils/page-permission-mixin.js');
const { MODULES } = require('../../utils/permission.js');
const { 
  fetchProductList, 
  searchProducts, 
  addProduct, 
  addStock, 
  reduceStock, 
  getProductDetail, 
  deleteProduct 
} = require('../../utils/inventory-api.js');

Page({
  behaviors: [themeChangeBehavior],
  
  // 混入权限检查方法
  ...pagePermissionMixin,
  
  data: {
    userInfo: null,
    activeTab: 'products', // 改为产品管理为主
    searchKeyword: '', // 统一搜索关键词
    productsList: [], // 当前显示的产品列表（可能是搜索结果）
    allProductsList: [], // 存储所有产品数据（用于前端搜索）
    currentPage: 1,
    pageSize: 10,
    totalCount: 0,
    hasMore: true,
    loading: false,
    refreshing: false,
    showCategoryPicker: false,
    showAddDialog: false,
    isSubmitting: false, // 防重复提交标志
    addForm: {
      productCode: '',
      productName: '',
      color: '',
      quantity: '',
      remark: ''
    },
    statistics: {
      totalProducts: 0,
      lowStockAlerts: 0,
      totalValue: 0
    }
  },

  onLoad() {
    // 检查页面权限
    this.onPageLoadPermissionCheck(MODULES.INVENTORY_MANAGEMENT);
    
    this.loadUserInfo();
    this.loadProductsList();
  },

  onShow() {
    // 页面显示时刷新数据
    if (this.data.productsList.length > 0) {
      this.loadProductsList();
    }
  },

  onPullDownRefresh() {
    this.refreshProductsList();
    wx.stopPullDownRefresh();
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreProducts();
    }
  },

  loadUserInfo() {
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo || (userInfo.role !== 3 && userInfo.type !== 3)) {
      wx.showToast({
        title: '权限不足',
        icon: 'none'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
      return;
    }
    this.setData({ userInfo });
  },

  // 加载产品列表
  async loadProductsList(refresh = false) {
    if (refresh) {
      this.setData({ 
        refreshing: true,
        currentPage: 1,
        hasMore: true,
        allProductsList: [] // 重置所有产品数据
      });
    } else if (this.data.loading) {
      return;
    }

    this.setData({ loading: true });

    try {
      const result = await fetchProductList(this.data.currentPage, this.data.pageSize);
      
      if (result.message == "操作成功" ) {
        const { list = [], total = 0, pageNum = 1, hasNextPage = false } = result.data;
        
        // 处理数据，添加状态标识和格式化时间
        const processedList = list.map(item => ({
          ...item,
          status: this.getStockStatus(item.currentStock),
          displayName: `${item.productName} - ${item.color}`,
          createTimeFormatted: this.formatDateTime(item.createTime),
          updateTimeFormatted: this.formatDateTime(item.updateTime)
        }));

        if (refresh || this.data.currentPage === 1) {
          // 刷新或首次加载
          this.setData({
            productsList: processedList,
            allProductsList: processedList, // 保存完整数据用于前端搜索
            totalCount: total,
            currentPage: pageNum,
            hasMore: hasNextPage
          });
        } else {
          // 加载更多
          const newProductsList = [...this.data.productsList, ...processedList];
          const newAllProductsList = [...this.data.allProductsList, ...processedList];
          this.setData({
            productsList: newProductsList,
            allProductsList: newAllProductsList, // 累积所有数据
            currentPage: pageNum,
            hasMore: hasNextPage
          });
        }

        this.updateStatistics();
      } else {
        wx.showToast({
          title: result.message || '加载失败',
          icon: 'none'
        });
      }
    } catch (error) {

      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ 
        loading: false, 
        refreshing: false 
      });
    }
  },

  // 刷新产品列表
  refreshProductsList() {
    this.loadProductsList();
  },

  // 加载更多产品
  loadMoreProducts() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({ currentPage: this.data.currentPage + 1 });
      this.loadProductsList();
    }
  },

  // 获取库存状态
  getStockStatus(currentStock) {
    if (currentStock === 0) {
      return 'out';
    } else if (currentStock < 50) { // 这里可以根据实际业务调整阈值
      return 'low';
    }
    return 'normal';
  },

  // 更新统计信息
  updateStatistics() {
    const { productsList } = this.data;
    
    const totalProducts = productsList.length;
    const lowStockAlerts = productsList.filter(item => 
      item.status === 'low' || item.status === 'out'
    ).length;
    
    // 计算总价值（这里假设每个产品都有价值，可以根据实际情况调整）
    const totalValue = productsList.reduce((sum, item) => {
      // 如果没有单价，可以用0或其他默认值
      const unitPrice = item.unitPrice || item.costPrice || 0;
      return sum + (item.currentStock * unitPrice);
    }, 0);

    this.setData({
      statistics: {
        totalProducts,
        lowStockAlerts,
        totalValue: Math.round(totalValue)
      }
    });
  },

  onTabChange(e) {
    const { value } = e.detail;
    this.setData({ activeTab: value });
  },

  // 搜索输入处理
  onSearchInput(e) {
    const keyword = e.detail.value || '';
    this.setData({ searchKeyword: keyword });
    
    // 防抖搜索 - 用户停止输入500ms后自动搜索
    clearTimeout(this.searchTimer);
    this.searchTimer = setTimeout(() => {
      this.performSearch();
    }, 500);
  },

  // 搜索确认（点击搜索按钮或键盘搜索）
  onSearchConfirm() {
    clearTimeout(this.searchTimer);
    this.performSearch();
  },

  // 执行前端搜索
  performSearch() {
    const { searchKeyword, allProductsList } = this.data;
    
    // 如果搜索关键词为空，显示所有产品
    if (!searchKeyword || searchKeyword.trim() === '') {
      this.setData({
        productsList: [...allProductsList],
        totalCount: allProductsList.length
      });
      this.updateStatistics();
      return;
    }

    const trimmedKeyword = searchKeyword.trim().toLowerCase();

    // 前端过滤搜索
    const filteredList = allProductsList.filter(item => {
      const productCode = (item.productCode || '').toLowerCase();
      const productName = (item.productName || '').toLowerCase();
      const color = (item.color || '').toLowerCase();
      const displayName = (item.displayName || '').toLowerCase();
      
      // 支持多字段搜索
      return productCode.includes(trimmedKeyword) || 
             productName.includes(trimmedKeyword) || 
             color.includes(trimmedKeyword) ||
             displayName.includes(trimmedKeyword);
    });

    // 为搜索结果添加匹配类型标记
    const processedList = filteredList.map(item => ({
      ...item,
      matchType: this.getMatchType(item, trimmedKeyword)
    }));

    this.setData({
      productsList: processedList,
      totalCount: processedList.length,
      hasMore: false // 前端搜索不需要分页
    });

    this.updateStatistics();

    // 显示搜索结果提示
    if (processedList.length === 0) {
      wx.showToast({
        title: `未找到"${searchKeyword.trim()}"相关产品`,
        icon: 'none',
        duration: 2000
      });
    } else {
    }
  },

  // 判断匹配类型（用于高亮显示）
  getMatchType(item, keyword) {
    const lowerKeyword = keyword.toLowerCase();
    const productCode = (item.productCode || '').toLowerCase();
    const productName = (item.productName || '').toLowerCase();
    const color = (item.color || '').toLowerCase();
    
    const codeMatch = productCode.includes(lowerKeyword);
    const nameMatch = productName.includes(lowerKeyword);
    const colorMatch = color.includes(lowerKeyword);
    
    if (codeMatch && nameMatch) {
      return 'both'; // 编号和名称都匹配
    } else if (codeMatch && colorMatch) {
      return 'both'; // 编号和颜色都匹配
    } else if (nameMatch && colorMatch) {
      return 'both'; // 名称和颜色都匹配
    } else if (codeMatch) {
      return 'code'; // 只有编号匹配
    } else if (nameMatch) {
      return 'name'; // 只有名称匹配
    } else if (colorMatch) {
      return 'color'; // 只有颜色匹配
    }
    return 'none'; // 无直接匹配
  },

  // 清除搜索
  onClearSearch() {
    clearTimeout(this.searchTimer);
    this.setData({ 
      searchKeyword: '',
      productsList: [...this.data.allProductsList],
      totalCount: this.data.allProductsList.length
    });
    this.updateStatistics();
  },

  getStatusText(status) {
    const statusMap = {
      'normal': '正常',
      'low': '库存不足',
      'out': '缺货'
    };
    return statusMap[status] || '未知';
  },

  getStatusColor(status) {
    const colorMap = {
      'normal': '#00A870',
      'low': '#E37318',
      'out': '#D54941'
    };
    return colorMap[status] || '#999';
  },

  // 库存入库
  onStockIn(e) {
    const { id } = e.currentTarget.dataset;
    const product = this.data.productsList.find(item => item.id === id);
    
    if (!product) {
      wx.showToast({
        title: '产品不存在',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '入库操作',
      editable: true,
      placeholderText: '请输入数量...',
      success: (res) => {
        if (res.confirm && res.content.trim()) {
          const quantity = parseInt(res.content.trim());
          if (quantity > 0) {
            this.processStockIn(product, quantity);
          } else {
            wx.showToast({
              title: '请输入有效数量',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 处理入库
  async processStockIn(product, quantity) {
    wx.showLoading({ title: '处理中...' });
    
    try {
      const params = {
        productCode: product.productCode,
        color: product.color,
        quantity: quantity
      };

      const result = await addStock(params);
      
      if (result.message == "操作成功") {
        wx.showToast({
          title: `入库成功`,
          icon: 'success',
          duration: 2000
        });
        
        // 优化：立即更新本地数据，提升用户体验
        this.updateProductStock(product.id, product.currentStock + quantity);
        
        // 延迟刷新完整数据，确保数据一致性
        setTimeout(() => {
          this.loadProductsList();
        }, 1000);
        
      } else {
        wx.showToast({
          title: result.message || '入库失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('入库操作失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 库存出库
  onStockOut(e) {
    const { id } = e.currentTarget.dataset;
    const product = this.data.productsList.find(item => item.id === id);
    
    if (!product) {
      wx.showToast({
        title: '产品不存在',
        icon: 'none'
      });
      return;
    }
    
    wx.showModal({
      title: '出库操作',
      editable: true,
      placeholderText: '请输入数量...',
      success: (res) => {
        if (res.confirm && res.content.trim()) {
          const quantity = parseInt(res.content.trim());
          if (quantity > 0) {
            if (quantity > product.currentStock) {
              wx.showToast({
                title: '出库数量不能大于当前库存',
                icon: 'none'
              });
              return;
            }
            this.processStockOut(product, quantity);
          } else {
            wx.showToast({
              title: '请输入有效数量',
              icon: 'none'
            });
          }
        }
      }
    });
  },

  // 处理出库
  async processStockOut(product, quantity) {
    wx.showLoading({ title: '处理中...' });
    
    try {
      const params = {
        productCode: product.productCode,
        color: product.color,
        quantity: quantity
      };

      const result = await reduceStock(params);
      
      if (result.message == "操作成功") {
        wx.showToast({
          title: `出库成功`,
          icon: 'success',
          duration: 2000
        });
        
        // 优化：立即更新本地数据，提升用户体验
        this.updateProductStock(product.id, product.currentStock - quantity);
        
        // 延迟刷新完整数据，确保数据一致性
        setTimeout(() => {
          this.loadProductsList();
        }, 1000);
        
      } else {
        wx.showToast({
          title: result.message || '出库失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('出库操作失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    } finally {
      wx.hideLoading();
    }
  },

  // 更新产品库存（立即更新UI）
  updateProductStock(productId, newStock) {
    const { productsList, allProductsList } = this.data;
    
    // 更新当前显示的列表
    const updatedProductsList = productsList.map(product => {
      if (product.id === productId) {
        const updatedProduct = {
          ...product,
          currentStock: newStock,
          status: this.getStockStatus(newStock),
          updateTimeFormatted: this.formatDateTime(new Date().toISOString())
        };
        return updatedProduct;
      }
      return product;
    });
    
    // 更新完整列表
    const updatedAllProductsList = allProductsList.map(product => {
      if (product.id === productId) {
        const updatedProduct = {
          ...product,
          currentStock: newStock,
          status: this.getStockStatus(newStock),
          updateTimeFormatted: this.formatDateTime(new Date().toISOString())
        };
        return updatedProduct;
      }
      return product;
    });
    
    // 更新数据
    this.setData({
      productsList: updatedProductsList,
      allProductsList: updatedAllProductsList
    });
    
    // 更新统计信息
    this.updateStatistics();

  },

  onShowAddDialog() {
    this.setData({ 
      showAddDialog: true,
      isSubmitting: false // 重置提交状态
    });
  },

  // 确认添加产品
  async onAddConfirm() {
    // 防重复提交
    if (this.data.isSubmitting) {
      wx.showToast({
        title: '正在提交中，请稍候...',
        icon: 'none'
      });
      return;
    }

    // 验证表单数据
    const { addForm } = this.data;
    if (!addForm.productCode || !addForm.productName || !addForm.color || !addForm.quantity) {
      wx.showToast({
        title: '请填写必填信息',
        icon: 'none'
      });
      return;
    }

    // 验证数量为正整数
    const quantity = parseInt(addForm.quantity);
    if (isNaN(quantity) || quantity < 0) {
      wx.showToast({
        title: '请输入有效的库存数量',
        icon: 'none'
      });
      return;
    }

    // 检查是否已存在相同的产品编号和颜色组合
    const existingProduct = this.data.allProductsList.find(item => 
      item.productCode.trim().toLowerCase() === addForm.productCode.trim().toLowerCase() &&
      item.color.trim().toLowerCase() === addForm.color.trim().toLowerCase()
    );



    if (existingProduct) {
      wx.showModal({
        title: '重复产品提醒',
        content: `产品编号"${addForm.productCode}"的"${addForm.color}"颜色已存在，确定要继续添加吗？`,
        confirmText: '继续添加',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.submitAddProduct();
          }
        }
      });
      return;
    }

    // 没有重复，直接提交
    this.submitAddProduct();
  },

  // 提交添加产品
  async submitAddProduct() {
    const { addForm } = this.data;
    
    // 设置提交状态
    this.setData({ isSubmitting: true });
    wx.showLoading({ title: '添加中...' });
    
    try {
      const params = {
        productCode: addForm.productCode.trim(),
        productName: addForm.productName.trim(),
        color: addForm.color.trim(),
        quantity: parseInt(addForm.quantity),
        remark: addForm.remark.trim() || ''
      };

      const result = await addProduct(params);
      
      if (result.message == "操作成功") {
        // 成功后关闭弹窗并重置表单
        this.setData({ 
          showAddDialog: false,
          isSubmitting: false // 重置提交状态
        });
        this.resetAddForm();
        
        wx.showToast({
          title: '添加成功',
          icon: 'success',
          duration: 1500
        });
        
        // 延迟刷新，让用户看到成功反馈
        setTimeout(() => {
          wx.showToast({
            title: '正在更新列表...',
            icon: 'loading',
            duration: 1000
          });
          this.loadProductsList(true);
        }, 1500);
        
      } else {
        // 显示具体的错误信息
        const errorMsg = result.message || '添加失败，请检查输入信息';
        wx.showModal({
          title: '添加失败',
          content: errorMsg,
          showCancel: false,
          confirmText: '我知道了'
        });
      }
    } catch (error) {

      wx.showModal({
        title: '网络错误',
        content: '网络连接异常，请检查网络后重试',
        showCancel: false,
        confirmText: '我知道了'
      });
    } finally {
      wx.hideLoading();
      // 重置提交状态
      this.setData({ isSubmitting: false });
    }
  },

  onAddCancel() {
    this.setData({ 
      showAddDialog: false,
      isSubmitting: false // 重置提交状态
    });
    this.resetAddForm();
  },

  // 重置添加表单
  resetAddForm() {
    this.setData({
      addForm: {
        productCode: '',
        productName: '',
        color: '',
        quantity: '',
        remark: ''
      }
    });
  },

  onAddFormInput(e) {
    const { field } = e.currentTarget.dataset;
    // TDesign Input组件的事件结构
    const value = e.detail.value || '';
    this.setData({
      [`addForm.${field}`]: value
    });
  },

  // 查看产品详情（变化记录）
  onItemDetail(e) {
    const { id } = e.currentTarget.dataset;
    const product = this.data.productsList.find(item => item.id === id);
    
    if (!product) {
      wx.showToast({
        title: '产品不存在',
        icon: 'none'
      });
      return;
    }

    // 跳转到详情页面
    const productInfo = encodeURIComponent(JSON.stringify(product));
    wx.navigateTo({
      url: `/pages/inventory-detail/inventory-detail?productInfo=${productInfo}`
    });
  },



  // 格式化日期时间
  formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return '';
    
    try {
      const date = new Date(dateTimeStr);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        return dateTimeStr; // 如果无法解析，返回原字符串
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    } catch (error) {

      return dateTimeStr; // 发生错误时返回原字符串
    }
  },

  // 删除产品
  async onDeleteProduct(e) {
    const { id } = e.currentTarget.dataset;
    const product = this.data.productsList.find(item => item.id === id);
    
    if (!product) {
      wx.showToast({
        title: '产品不存在',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '删除产品',
      content: `确定要删除产品"${product.displayName}"吗？此操作不可恢复。`,
      confirmText: '删除',
      confirmColor: '#D54941',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' });
          
          try {
            const params = {
              id: product.id.toString(),
              productCode: product.productCode,
              color: product.color
            };

            const result = await deleteProduct(params);
            
            if (result.message == "操作成功") {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                duration: 2000
              });
              
              // 优化：立即从当前列表中移除该产品，然后更新统计
              this.removeProductFromList(product.id);
              
              // 延迟刷新完整数据，确保数据一致性
              setTimeout(() => {
                this.loadProductsList(true);
              }, 1000);
              
            } else {
              wx.showToast({
                title: result.message || '删除失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('删除产品失败:', error);
            wx.showToast({
              title: '网络错误，请重试',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  // 从当前列表中移除产品（立即更新UI）
  removeProductFromList(productId) {
    const { productsList, allProductsList } = this.data;
    
    // 从当前显示的列表中移除
    const newProductsList = productsList.filter(item => item.id !== productId);
    
    // 从完整列表中移除
    const newAllProductsList = allProductsList.filter(item => item.id !== productId);
    
    // 更新列表和统计数据
    this.setData({
      productsList: newProductsList,
      allProductsList: newAllProductsList,
      totalCount: newProductsList.length
    });
    
    // 更新统计信息
    this.updateStatistics();

  },

  // 优化的批量删除功能（如果需要的话）
  async onBatchDelete(productIds) {
    if (!productIds || productIds.length === 0) {
      wx.showToast({
        title: '请选择要删除的产品',
        icon: 'none'
      });
      return;
    }

    wx.showModal({
      title: '批量删除',
      content: `确定要删除选中的 ${productIds.length} 个产品吗？此操作不可恢复。`,
      confirmText: '删除',
      confirmColor: '#D54941',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '批量删除中...' });
          
          try {
            let successCount = 0;
            let failCount = 0;
            
            // 逐个删除产品
            for (const productId of productIds) {
              const product = this.data.productsList.find(item => item.id === productId);
              if (product) {
                try {
                  const params = {
                    id: product.id.toString(),
                    productCode: product.productCode,
                    color: product.color
                  };
                  
                  const result = await deleteProduct(params);
                  if (result.message == "操作成功") {
                    successCount++;
                    // 立即从列表中移除
                    this.removeProductFromList(productId);
                  } else {
                    failCount++;
                  }
                } catch (error) {
                  failCount++;
                }
              }
            }
            
            // 显示批量删除结果
            if (failCount === 0) {
              wx.showToast({
                title: `批量删除成功，共 ${successCount} 个`,
                icon: 'success',
                duration: 2000
              });
            } else {
              wx.showToast({
                title: `删除完成：成功 ${successCount} 个，失败 ${failCount} 个`,
                icon: 'none',
                duration: 3000
              });
            }
            
            // 最终刷新数据
            setTimeout(() => {
              this.loadProductsList();
            }, 1000);
            
          } catch (error) {
            console.error('批量删除失败:', error);
            wx.showToast({
              title: '批量删除失败',
              icon: 'none'
            });
          } finally {
            wx.hideLoading();
          }
        }
      }
    });
  },

  onUnload() {
    // 清理定时器
    if (this.searchTimer) {
      clearTimeout(this.searchTimer);
    }
    // 清理刷新定时器
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
    }
  },

  // 通用的智能列表更新方法
  smartUpdateList(options = {}) {
    const {
      showLoading = false,
      loadingText = '更新中...',
      delay = 1000,
      successText = '更新完成'
    } = options;
    
    // 清除之前的定时器
    if (this.refreshTimer) {
      clearTimeout(this.refreshTimer);
    }
    
    if (showLoading) {
      wx.showToast({
        title: loadingText,
        icon: 'loading',
        duration: delay
      });
    }
    
    this.refreshTimer = setTimeout(() => {
      this.loadProductsList(true);
      
      if (successText) {
        setTimeout(() => {
          wx.showToast({
            title: successText,
            icon: 'none',
            duration: 1000
          });
        }, 500);
      }
    }, delay);
  }
}); 